package com.ynny.h14.Controller;

import com.ynny.h14.Entity.R;
import com.ynny.h14.Entity.Users;
import com.ynny.h14.Service.UsersService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.List;

@RestController
@RequestMapping("/login")
public class UsersController {
    @Autowired
    UsersService usersService;

    private static final String SESSION_USERS = "SESSION_USERS";

    @GetMapping
    public R login(HttpServletResponse response) throws IOException {
        response.sendRedirect("/static/views/login.html");
        return R.error(440 , "请先登录");
    }

    @GetMapping("/find")
    public List<Users> find(){
        return usersService.findAll(null);
    }

    @PostMapping
    public R login(@RequestBody Users users ,HttpSession session) {
        if(users!=null){
            R login = usersService.login(users);
            if (login.getCode()==200){
                session.setAttribute(SESSION_USERS,login.getData());//将用户信息存储在session域中
                return R.ok(login.getData());
            }
            return login;
        }
        return R.error(414,"数据为空！");
    }

    @PostMapping("/out")
    public R logout(HttpSession session){

        session.removeAttribute(SESSION_USERS);//清除存储在session域中的用户信息

        return R.ok(null);
    }
}
